package coms.itboyes.bycommon.base;

import android.annotation.SuppressLint;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import coms.itboyes.bycommon.loadutil.LoadingDialog;


/**
 * 继承自该Fragment的类不需要findViewById，在onActivityCreated中调用super.onActivityCreated()
 * 后即可直接使用全局的控件了，具体使用方式参看 {@link com.itboye.sunsun.support.BaseActivity}
 * 
 * @author Young
 * 
 */
public class BaseFragment extends Fragment {
	LoadingDialog progressDialog = null;

	// @Override
	// public View onCreateView(LayoutInflater inflater,
	// @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
	// // TODO Auto-generated method stub
	// View v= super.onCreateView(inflater, container, savedInstanceState);
	//
	// smartInject(v);
	// return v;
	// }
	//
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		smartInject(getView());
		progressDialog = new LoadingDialog();
	}

	public void onResume() {
	    super.onResume();
	}
	public void onPause() {
	    super.onPause();
	}
	
	protected void smartInject(View view) {
		try {
			Class<? extends Fragment> clz = getClass();
			while (clz != BaseFragment.class) {
				Field[] fs = clz.getDeclaredFields();
				Resources res = getResources();
				String packageName = getActivity().getPackageName();
				for (Field field : fs) {
					if (!View.class.isAssignableFrom(field.getType())) {
						continue;
					}
					int viewId = res.getIdentifier(field.getName(), "id",
							packageName);
					if (viewId == 0)
						continue;
					field.setAccessible(true);
					try {
						View v = view.findViewById(viewId);
						field.set(this, v);
						Class<?> c = field.getType();
						Method m = c.getMethod("setOnClickListener",
								View.OnClickListener.class);
						m.invoke(v, this);
					} catch (Throwable e) {
					}
					field.setAccessible(false);

				}

				clz = (Class<? extends Fragment>) clz.getSuperclass();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 显示进度对话框,带有消息 flag 是否可以取消
	 */
	@SuppressLint("NewApi")
	public void showProgressDialog(String message, boolean flag) {
		if (progressDialog == null)
			return;
		setProgressDialogMessage(message);

		progressDialog.show(getActivity().getFragmentManager(), message);
		progressDialog.setCancelable(flag);

	}

	/**
	 * 设置进度对话框消息
	 * 
	 * @param message
	 */
	public void setProgressDialogMessage(String message) {
		progressDialog.setMsg(message);
	}

	/**
	 * 关闭进度对话框
	 */
	@SuppressLint("NewApi")
	public void closeProgressDialog() {
		if (progressDialog != null) {
			if (progressDialog.getDialog().isShowing()) {
				progressDialog.dismiss();
			}
		}
	}
}
